from utils import center_window
import tkinter as tk
from tkinter import messagebox, filedialog, Toplevel
from tkinter.ttk import Combobox, Progressbar
import threading
import pyperclip
from file_utils import extract_code_from_files
from http_utils import send_post_request_with_loading


def select_folder_and_language():
    folder_selected = filedialog.askdirectory(title="请选择一个文件夹")
    if not folder_selected:
        return

    def on_language_selected():
        # 在主线程中获取语言选择
        language = combo_language.get()

        # 创建加载窗口
        loading_window = Toplevel()
        loading_window.title("处理中")
        center_window(loading_window, 200, 100)  # 居中窗口

        loading_label = tk.Label(loading_window, text="加载中，请稍候...")
        loading_label.pack(pady=20)

        def process_code(language):
            if language not in ['Java', 'Python', 'C++']:
                messagebox.showerror("错误", "请选择有效的选项")
                loading_window.destroy()
                return

            # 根据选择设置文件扩展名
            if language == 'Java':
                extension = '.java'
            elif language == 'Python':
                extension = '.py'
            else:  # C++
                extension = '.cpp'

            code_snippets = extract_code_from_files(folder_selected, extension)

            if code_snippets:
                full_code = "\n".join(code_snippets)
                pyperclip.copy(full_code)

                success_message = f"代码已复制到剪贴板，共计 {len(code_snippets)} 段"
                messagebox.showinfo("成功", success_message)

                if messagebox.askyesno("发送HTTP请求", "是否发送POST请求到服务器？"):
                    threading.Thread(target=send_post_request_with_loading, args=(full_code,)).start()
            else:
                messagebox.showwarning("警告", "未找到任何代码文件")

            loading_window.destroy()

        # 开始线程，以语言作为参数传递
        threading.Thread(target=process_code, args=(language,)).start()

        language_window.destroy()

    language_window = Toplevel()
    language_window.title("请选择语言")
    center_window(language_window, 250, 100)

    # 添加C++选项
    combo_language = Combobox(language_window, values=["Java", "Python", "C++"], state="readonly")
    combo_language.set("Java")  # 初始显示Java
    combo_language.pack(pady=10)

    btn_confirm = tk.Button(language_window, text="确认", command=on_language_selected)
    btn_confirm.pack(pady=5)


def create_gui():
    root = tk.Tk()
    root.title("代码提取工具")
    center_window(root, 300, 200)

    btn_select_folder = tk.Button(root, text="选择文件夹", command=select_folder_and_language)
    btn_select_folder.place(relx=0.5, rely=0.5, anchor=tk.CENTER)

    return root
